<template>
  <view class="search-view">
    <view class="search-input">
      <image src="/static/sousuo.png" mode="widthFix" />
      <input type="text" placeholder="搜索商品" placeholder-class="input-color" confirm-type="search" focus
        v-model="keyword" @confirm="search" @input="search" />
    </view>
    <view style="height: 70rpx;"></view>

    <view class="goods-infor" v-for="(goods, goods_index) in goodsList" :key="goods._id" @tap="goDetail(goods._id)">
      <image :src="goods.image" mode="aspectFill" />
      <view class="product-name">
        <text class="googs-name">{{ goods.name }}</text>
        <text class="googs-intro overflow-text">
          {{ goods.description }}
        </text>
        <view class="select-goods">
          <view class="goods-price">
            <text>￥{{ goods.price }}</text>
            <text>起</text>
          </view>
          <block v-if="goods.stock">
            <view class="select-quantity" v-if="goods.attribute?.length">
              <button>选规格</button>
              <text v-if="goods.quantity">{{ goods.quantity }}</text>
            </view>
            <view class="select-goods single-goods" v-else>
              <image src="/static/jian-goods.png" mode="widthFix" v-if="goods.quantity"
                @tap.stop="handleProduct(goods_index, -1)" />
              <text v-if="goods.quantity">{{ goods.quantity }}</text>
              <image src="/static/jia-goods.png" mode="widthFix" @tap.stop="handleProduct(goods_index, 1)" />
            </view>
          </block>
          <view v-else><button disabled>已售罄</button></view>
        </view>
      </view>
    </view>
    <Tips v-if="nodata" />
  </view>
</template>
<script setup lang="ts">
import request from "@/api/request";
import { useStore } from "@/store";
import { ref, watch } from 'vue';
import Decimal from "decimal.js";
import type { GoodsInfo } from "@/types";
import Tips from "@/component/tipes.vue";
const keyword = ref("");
const goodsList = ref<GoodsInfo[]>();
const nodata = ref(false);
const store = useStore();
const search = async () => {
  if (keyword.value.trim()) {
    const { data } = await request<GoodsInfo[]>("/searchGoodsList", { keyword: keyword.value });
    goodsList.value = data;
    nodata.value = false;
  } else {
    goodsList.value = [];
    nodata.value = true;
  }
};
const goDetail = (_id: string) => {
  uni.navigateTo({ url: "/pages/productDetail/index?_id=" + _id });
};

const handleProduct = (goodsIndex: number, num: -1 | 1) => {
  const goods = goodsList.value![goodsIndex];
  goods.quantity += num;
  const params = {
    categoryId: goods!.categoryId,
    goodsId: goods!._id,
    name: goods!.name,
    image: goods!.image,
    price: goods.price,
    specs: [],
    sid: [],
    quantity: num,
    attrId: "",
    totalPrice: Decimal(goods.price).times(new Decimal(goods!.quantity)),
  };
  store.addTocart(params);
  console.log("cxcxc", params, Number(params.totalPrice));

  console.log(store.cartItems);
};

// 监听购物车每一个商品数量的变化，从而根据下标找到当前页面商品并更新
watch(() => store.cartItems.map(item => item.quantity), (newValue, oldValue) => {
  // [2,1],[3,1]
  if (newValue.length) {
    for (let i = 0; i < newValue.length; i++) {
      if (newValue[i] != oldValue[i]) {
        const goodsItem = store.cartItems[i];
        const findItem = goodsList.value?.find(item => item._id === goodsItem.goodsId);
        // 有规格商品，购物车查找相同goods_id的商品做数量累加
        if (findItem?.attribute.length) {
          const totalQuantity = store.cartItems.filter(item => item.goodsId === findItem._id).reduce((a, b) => a + b.quantity, 0);
          findItem.quantity = totalQuantity;
        } else {
          findItem!.quantity = newValue[i];
        }
        return;
      }
    }

  } else {
    if (goodsList.value?.length) {
      goodsList.value.forEach(item => item.quantity = 0);
    }
  }
});
</script>
<style>
.search-view {
  background-color: #ffffff;
  height: 70rpx;
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 99;
  padding-right: 20rpx;
  padding-bottom: 10rpx;
}

.search-input input {
  height: 70rpx;
}

.secrch-goods {
  display: flex;
  margin: 20rpx;
}

.secrch-goods image {
  width: 120rpx;
  height: 120rpx;
  border-radius: 15rpx;
}

.search-goods-name {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  padding: 0 20rpx;
}

.search-goods-name text:nth-child(1) {
  font-weight: bold;
  font-size: 29rpx;
}

.search-goods-name text:nth-child(2) {
  font-size: 24rpx;
  font-weight: bold;
}

.secrch-goods button {
  margin: 0;
  align-self: flex-end;
  font-size: 28rpx;
  background-color: #214bd5;
  color: #ffffff;
  padding: 5rpx 20rpx;
}

.no-data {
  display: flex;
  flex-direction: column;
  align-items: center;
  color: #b8b8b8;
  padding-top: 200rpx;
}

.no-data image {
  width: 300rpx;
}

.goods-infor {
  display: flex;
  align-items: center;
  padding-top: 35rpx;
}

.goods-infor image {
  width: 170rpx;
  height: 170rpx;
  border-radius: 15rpx;
}

.product-name {
  flex: 1;
  padding-left: 15rpx;
}

.googs-name {
  font-weight: bold;
  font-size: 29rpx;
}

.googs-intro {
  line-height: 1.4;
  color: #b8b8b8;
  font-size: 25rpx;
  margin: 13rpx 0;
}

.select-goods {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.goods-price {
  display: flex;
  flex: 1;
}

.goods-price text:nth-child(1) {
  font-size: 30rpx;
  font-weight: bold;
  padding-right: 10rpx;
}

.goods-price text:nth-child(2) {
  font-size: 24rpx;
  color: #b8b8b8;
  align-self: flex-end;
}

.select-quantity {
  position: relative;
}

.select-quantity button {
  font-size: 28rpx;
  line-height: inherit;
  background-color: #214bd5;
  color: #ffffff;
  padding: 5rpx 20rpx;
  border-radius: 40rpx;
}

.select-quantity text {
  position: absolute;
  top: -7rpx;
  right: 0;
  background: bisque;
  border-radius: 50%;
  width: 30rpx;
  height: 30rpx;
  font-size: 18rpx;
  text-align: center;
  line-height: 30rpx;
}

.single-goods image {
  width: 45rpx;
  height: 45rpx;
}

.single-goods text {
  font-size: 26rpx;
  width: 63rpx;
  text-align: center;
}
</style>